import BigNumber from "bignumber.js";

// 下载文件
export function handleDownload(file) {
  let finalUrl = "https://xinmanrui.com/eduWebSiteApi" + file.fileUrl;
  changeBlob(finalUrl).then(res => {
    saveAs(res, file.name);
  });
}

function changeBlob(url) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
}

function saveAs(blob, filename) {
  var link = document.createElement("a");
  link.href = window.URL.createObjectURL(blob);
  link.download = filename;
  link.click();
}

export const numberFormat = number => {
  if (!number) {
    return "--";
  }
  number = number + "";

  const re = /^(-?\d+)(\d{3})(\.?\d*)/;
  while (re.test(number)) {
    number = number.replace(re, "$1,$2$3");
  }

  return number;
};

/**
 * treeData 分为上下级
 * @param treeData 原数据
 * @param parentIdKey
 * @param parentNamekey
 * @param itemNameKey
 * @returns
 */
export function dealTreeList(
  treeData: Array<any>,
  parentIdKey: string,
  parentNamekey: string,
  itemNameKey: string
) {
  let tempList = [];
  treeData.forEach(item => {
    let obj = tempList.find(v => v.id == item[parentIdKey]);
    if (obj) {
      obj.children.push({
        id: item.id,
        label: item[itemNameKey] || "--"
      });
    } else {
      tempList.push({
        id: item[parentIdKey],
        label: item[parentNamekey] || "--",
        children: [
          {
            id: item.id,
            label: item[itemNameKey] || "--"
          }
        ]
      });
    }
  });
  return tempList;
}

// 数据 * 100
export function dealDataRide(data, flag = 100, decimal = undefined) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return decimal
      ? data.times(flag).toFormat(decimal)
      : data.times(flag).toNumber();
  }
}

// 数据 / 100
export function dealDataExcept(data, flag = 100, decimal = undefined) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return decimal
      ? data.div(flag).toFormat(decimal)
      : data.div(flag).toNumber();
  }
}

// 处理相加
export function dealDataAdd(data, flag = 0) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return data.plus(flag || 0).toNumber();
  }
}

// 处理相减
export function dealDataCut(data, flag = 0) {
  if (!data) {
    return "";
  } else {
    data = new BigNumber(data);
    return data.minus(flag || 0).toNumber();
  }
}

let commonUtil = {
  dealDataRide, // 数据乘 默认10 *10
  dealDataExcept, // 数据除 默认10 /10
  dealDataAdd, // 数据相加
  dealDataCut // 数据相减
};

export default commonUtil;
